<template>
  <view class="message-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-content">
        <view class="nav-back" @tap="goBack">
          <uni-icons type="left" size="20" color="#333"></uni-icons>
        </view>
        <view class="message-tabs">
          <view class="tab" :class="{ active: false }" @click="navigateToPage('/pages/user/message/chat')">
            私信
          </view>
          <view class="tab" :class="{ active: true }" @click="navigateToPage('/pages/user/message/system')">
            系统消息
          </view>
        </view>
      </view>
    </view>
    
    <scroll-view 
      class="message-list" 
      scroll-y 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="messages.length === 0" class="empty-tip">
        暂无系统消息
      </view>
      <view v-else v-for="message in messages" :key="message.id" class="message-item">
        <uni-icons type="info-filled" size="40" color="#0066ff" class="message-icon"></uni-icons>
        <view class="content">
          <view class="header">
            <text class="title">{{ message.title }}</text>
            <text class="time">{{ formatTime(message.createTime) }}</text>
          </view>
          <view class="message-content">{{ message.content }}</view>
          <view class="footer">
            <text class="status" :class="{ read: message.isRead }">
              {{ message.isRead ? '已读' : '未读' }}
            </text>
            <text v-if="!message.isRead" class="action" @tap="markAsRead(message.id)">标记已读</text>
          </view>
        </view>
      </view>
      <view v-if="loading" class="loading">加载中...</view>
      <view v-if="!hasMore && messages.length > 0" class="no-more">没有更多了</view>
    </scroll-view>
  </view>
</template>

<script>
import { formatTime } from '@/utils/date'

export default {
  data() {
    return {
      messages: [],
      pageNum: 1,
      pageSize: 10,
      loading: false,
      hasMore: true,
      isRefreshing: false
    }
  },
  
  onShow() {
    this.loadMessages()
  },
  
  methods: {
    formatTime,
    
    navigateToPage(path) {
      uni.navigateTo({
        url: path
      })
    },
    
    async loadMessages(refresh = false) {
      if (this.loading) return
      
      try {
        this.loading = true
        if (refresh) {
          this.pageNum = 1
          this.messages = []
          this.hasMore = true
        }
        
        const res = await this.$api.message.getMessages({
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          type: 1 // 1-系统消息
        })
        
        if (res.code === 200 && res.data) {
          const { records, total } = res.data
          // 处理消息数据
          const formattedMessages = records.map(message => ({
            ...message,
            title: message.title || '系统通知',
            content: typeof message.content === 'string' ? 
              (message.content.startsWith('{') ? JSON.parse(message.content).content : message.content) 
              : message.content,
            createTime: message.createTime
          }))
          
          this.messages = refresh ? formattedMessages : [...this.messages, ...formattedMessages]
          this.hasMore = this.messages.length < total
          this.pageNum++
        }
      } catch (error) {
        console.error('获取系统消息失败:', error)
        uni.showToast({
          title: '获取消息失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        if (refresh) {
          this.isRefreshing = false
        }
      }
    },
    
    async markAsRead(messageId) {
      try {
        await this.$api.message.markAsRead(messageId)
        // 更新消息状态
        const message = this.messages.find(m => m.id === messageId)
        if (message) {
          message.isRead = true
          message.readTime = new Date()
        }
      } catch (error) {
        console.error('标记已读失败:', error)
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    },
    
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.loadMessages()
      }
    },
    
    async onRefresh() {
      this.isRefreshing = true
      await this.loadMessages(true)
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss">
.message-container {
  min-height: 100vh;
  background-color: #fff;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
  
  .nav-content {
    position: relative;
    padding-top: var(--status-bar-height);
    
    .nav-back {
      position: absolute;
      left: 30rpx;
      top: calc(var(--status-bar-height) + 24rpx);
      z-index: 1;
      padding: 20rpx;
    }
    
    .message-tabs {
      display: flex;
      justify-content: center;
      padding: 20rpx 120rpx;
      
      .tab {
        flex: 1;
        text-align: center;
        font-size: 32rpx;
        color: #666;
        position: relative;
        padding: 20rpx 0;
        
        &.active {
          color: #333;
          font-weight: bold;
          
          &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 40rpx;
            height: 4rpx;
            background-color: #333;
            border-radius: 2rpx;
          }
        }
      }
    }
  }
}

.message-list {
  padding: 20rpx;
  padding-top: 128rpx;
  height: calc(100vh - 128rpx);
  overflow-y: auto;
  
  .empty-tip {
    text-align: center;
    color: #999;
    font-size: 28rpx;
    padding: 60rpx 0;
  }
  
  .message-item {
    display: flex;
    align-items: flex-start;
    padding: 30rpx;
    background-color: #fff;
    border-bottom: 1rpx solid #f5f5f5;
    
    .message-icon {
      margin-right: 20rpx;
      flex-shrink: 0;
    }
    
    .content {
      flex: 1;
      overflow: hidden;
      
      .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;
        
        .title {
          font-size: 32rpx;
          color: #333;
          font-weight: 500;
        }
        
        .time {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .message-content {
        font-size: 28rpx;
        color: #666;
        line-height: 1.5;
        margin-bottom: 16rpx;
      }
      
      .footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .status {
          font-size: 24rpx;
          color: #ff5500;
          
          &.read {
            color: #999;
          }
        }
        
        .action {
          font-size: 24rpx;
          color: #0066ff;
          padding: 8rpx 20rpx;
          background: rgba(0, 102, 255, 0.1);
          border-radius: 24rpx;
        }
      }
    }
  }
  
  .loading,
  .no-more {
    text-align: center;
    color: #999;
    font-size: 24rpx;
    padding: 30rpx 0;
  }
}
</style> 